# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
  
  # 根據當前頁面回傳項目.
  def menu_line_item(name, options, html_options = nil)
    if current_page?(options)
      '<li class="active">' + 
        link_to(name, options) + 
        '</li>'
    else
      '<li>' + 
        link_to(name, options) + 
        '</li>'   
    end
  end
  
  # 回傳自訂格式的 Date .
  def date(date)
    h date.strftime('%Y/%m/%d %H:%M')
  end
  
  # 回傳自訂格式的貨幣格式.
  def price(money)
    h(price_format(money))
  end
  
  # 若未登入才會顯示最愛電報清單部份樣版.
  def favorite_partial
    unless login?
      render :partial => "shared/favorite", :object => @favorite
    end
  end
  
  # 根據傳入的值回傳價格字串.
  def price_format(price)
    "#{number_to_currency(price, :precision => 0)}元"
  end
  
  # 回傳加到最愛電報清單聯結.
  def add_to_favorite(computer)
    unless login?
      button_to '加到最愛', :controller => :show, :action => :add_to_favorite, :id => computer
    end
  end
  
  # 回傳清除最愛電報清單聯結.
  def clear_favorite
    unless login?
      button_to '砍掉重練', :controller => :show, :action => :clear_favorite
    end
  end
  
  # 回傳顯示最愛電報清單聯結.
  def show_favorite
    unless login?
      button_to '顯示全部', :controller => :show, :action => :show_favorite
    end
  end
  
  # 回傳新增電報連結.
  def add_computer()
    link_to image_tag('add_computer.gif'), new_computer_path
  end
  
  # 若已登入就回傳編輯電報連結.
  def edit_computer(computer)
    if login?
      link_to image_tag('edit_computer.gif'), edit_computer_path(computer)
    end
  end
  
  # 若已登入就回傳刪除電報連結.
  def delete_computer(computer)
    if login?
      link_to image_tag('del_computer.gif'), computer, :confirm => 'Are you sure?', :method => :delete
    end
  end
  
  # 回傳新增留言連結.
  def add_post(computer)
    # 將電報編號傳至 PostsController.new().
    link_to image_tag('add_post.gif'), :controller => :posts, :action => :new, :id => computer
  end
  
  # 若已登入就回傳編輯留言連結.
  def edit_post(post)
    if login?
      link_to image_tag('edit_post.gif'), edit_post_path(post)
    end
  end
  
  # 若已登入就回傳刪除留言連結.
  def delete_post(post)
    if login?
      link_to image_tag('del_post.gif'), post, :confirm => 'Are you sure?', :method => :delete
    end
  end
  
  # 從最愛電報中移除電報.
  def remove_from_favorite(computer)
    link_to image_tag('del_computer.gif'), :controller => :show, :action => :remove_from_favorite, :id => computer
  end
  
  protected
  
  # 登入回傳 true .
  def login?()
    login = true
    if session[:user_id].nil?
      login = false
    end
    login
  end
  
end
